/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.apache.bifromq.basecluster.messenger;

import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;

import org.apache.bifromq.basecluster.transport.Transport;
import io.reactivex.rxjava3.schedulers.Schedulers;
import java.net.InetSocketAddress;
import java.util.Collection;
import java.util.Collections;
import org.testng.annotations.Test;

public class MessengerTest {
    @Test
    public void shutdown() {
        Transport transport = Transport.builder()
            .env("test")
            .bindAddr(new InetSocketAddress("127.0.0.1", 0))
            .build();
        Messenger localMessenger = Messenger.builder()
            .transport(transport)
            .scheduler(Schedulers.io())
            .opts(new MessengerOptions())
            .build();
        localMessenger.start(new IRecipientSelector() {
            @Override
            public Collection<? extends IRecipient> selectForSpread(int limit) {
                return Collections.emptyList();
            }

            @Override
            public int clusterSize() {
                return 1;
            }
        });
        localMessenger.shutdown();
        localMessenger.shutdown();
        transport.shutdown().join();
    }

    @Test
    public void shutdownWithoutStart() {
        Transport transport = Transport.builder()
            .env("test")
            .bindAddr(new InetSocketAddress("127.0.0.1", 0))
            .build();
        Messenger localMessenger = Messenger.builder()
            .transport(transport)
            .scheduler(Schedulers.io())
            .opts(new MessengerOptions())
            .build();
        try {
            localMessenger.shutdown();
            fail();
        } catch (Throwable e) {
            assertTrue(e instanceof IllegalStateException);
        } finally {
            transport.shutdown().join();
        }
    }
}
